<template>
  <div>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="6">
          <a-input-search
            v-model="queryParam.username"
            placeholder="输入用户名查找"
            enter-button
            allowClear
            @search="getUserList"
          />
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="addUser">新增</a-button>
        </a-col>
      </a-row>
      <a-table
        :rowKey="(record) => record.ID"
        :columns="columns"
        :pagination="paginationOption"
        :dataSource="userList"
        bordered
      >
        <span slot="role" slot-scope="role">{{
          role == 1 ? "管理员" : "订阅者"
        }}</span>
        <template slot="action" slot-scope="data">
          <div class="actionSlot">
            <a-button
              type="primary"
              icon="edit"
              style="margin-right: 15px"
              @click="editUser(data.ID)"
              >编辑</a-button
            >
            <a-button
              type="danger"
              icon="delete"
              style="margin-right: 15px"
              @click="deleteUser(data.ID)"
              >删除</a-button
            >
            <a-button icon="info" type="info" @click="resetPwd(data.ID)"
              >重置密码</a-button
            >
          </div>
        </template>
      </a-table>
    </a-card>
    <!-- 用户新增 -->
    <a-modal
      title="新增用户"
      :visible="addUserVisible"
      @ok="addUserOk"
      @cancel="addUserCancel"
      closable
      destroyOnClose
    >
      <a-form-model :model="newUserInfo" :rules="userRules" ref="addUserRef">
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="newUserInfo.username"></a-input>
        </a-form-model-item>
        <a-form-model-item has-feedback label="密码" prop="password">
          <a-input-password v-model="newUserInfo.password"></a-input-password>
        </a-form-model-item>
        <a-form-model-item has-feedback label="确认密码" prop="comfirmPwd">
          <a-input-password v-model="newUserInfo.comfirmPwd"></a-input-password>
        </a-form-model-item>
        <a-form-model-item label="是否为管理员">
          <a-switch
            checked-children="管理员"
            un-checked-children="订阅者"
            @click="addSwitchClick"
            @change="addSwitchChange"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 编辑用户区 -->
    <a-modal
      title="编辑用户"
      :visible="editUserVisiable"
      @ok="editUserOk"
      @cancel="editUserCancel"
      closable
      destroyOnClose
    >
      <a-form-model :model="editUserInfo" :rules="userRules" ref="editUserRef">
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="editUserInfo.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="是否为管理员">
          <a-switch
            checked-children="管理员"
            :checked="editSwitch"
            @click="editSwitchClick"
            un-checked-children="订阅者"
            @change="editSwitchChange"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      columns: [
        {
          title: "ID",
          dataIndex: "ID",
          width: "5%",
          key: "id",
          align: "center",
        },
        {
          title: "用户名",
          dataIndex: "username",
          width: "20%",
          key: "username",
          align: "center",
        },
        {
          title: "角色",
          dataIndex: "role",
          width: "20%",
          key: "role",
          align: "center",

          scopedSlots: { customRender: "role" },
        },
        {
          title: "操作",
          width: "30%",
          key: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
        },
      ],
      paginationOption: {
        pageSizeOptions: ["2", "5", "10", "15"],
        defaultCurrent: 1,
        defaultPageSize: 2,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共${total}条`,
        onChange: (current, pageSize) => {
          this.paginationOption.defaultCurrent = current;
          this.getUserList();
        },
        onShowSizeChange: (current, size) => {
          this.paginationOption.defaultCurrent = 1;
          this.paginationOption.defaultPageSize = size;
          this.getUserList();
        },
      },
      queryParam: {
        username: "",
        pageSize: 2,
        pageNum: 1,
      },
      addUserVisible: false,
      editUserVisiable: false,
      newUserInfo: {
        id: 0,
        username: "",
        password: "",
        comfirmPwd: "",
        role: 2,
      },
      addSwitch: false,
      editSwitch: false,
      editUserInfo: {
        id: 0,
        username: "",
        role: 2,
      },
      userRules: {
        username: [
          { required: true, message: "请输入用户名" },
          { min: 4, max: 12, message: "用户名应在4到12位之间" },
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (this.newUserInfo.password == "") {
                callback(new Error("请输入密码"));
              }
              if (
                [...this.newUserInfo.password].length < 6 ||
                [...this.newUserInfo.password].length > 20
              ) {
                callback(new Error("密码应在6到20位之间"));
              } else callback();
            },
            trigger: "blur",
          },
        ],
        comfirmPwd: [
          {
            validator: (rule, value, callback) => {
              if (this.newUserInfo.comfirmPwd == "") {
                callback(new Error("请输入确认密码"));
              }
              if (this.newUserInfo.password != this.newUserInfo.comfirmPwd) {
                callback(new Error("两次密码不一致"));
              } else callback();
            },
            trigger: "blur",
          },
        ],
        role: [{ required: false }],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 分页获取用户信息
    async getUserList() {
      let that = this;
      const { data: res } = await this.$http.get("users", {
        params: {
          username: that.queryParam.username,
          pageNum: that.paginationOption.defaultCurrent,
          pageSize: that.paginationOption.defaultPageSize,
        },
      });

      if (res.status != 200) return this.$message.error(res.msg);
      this.userList = res.data;
      this.paginationOption.total = res.total;
    },
    // 删除用户
    deleteUser(id) {
      let that = this;
      this.$confirm({
        title: "确定要删除该用户吗?",
        content: "一旦删除无法恢复",
        okText: "Yes",
        okType: "danger",
        cancelText: "No",
        async onOk() {
          const { data: res } = await that.$http.delete(`user/${id}`);
          if (res.status != 200) return that.$message.error(res.msg);
          that.$message.success("删除成功");
          that.getUserList();
        },
        onCancel() {
          that.$message.info("已取消");
        },
      });
    },
    // 新增用户
    addUser() {
      this.addUserVisible = true;
    },
    // 新增用户同意回调
    addUserOk() {
      // 先校验新增用户信息
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return this.$message.error("参数不符合输入，请重新输入");
        // 发送新增用户请求
        const { data: res } = await this.$http.post("/user/add", {
          username: this.newUserInfo.username,
          password: this.newUserInfo.password,
          role: this.newUserInfo.role,
        });
        if (res.status != 200) return this.$message.error(res.msg);
        this.$message.success("添加用户成功");
        // 重置
        this.addUserVisible = false;
        this.$refs.addUserRef.resetFields();
        this.getUserList();
      });
    },
    // 新增用户取消回调
    addUserCancel() {
      this.addUserVisible = false;
      this.$refs.addUserRef.resetFields();
      this.$message.info("新增取消");
    },
    // 新增用户的角色
    addSwitchChange(checked) {
      if (checked) {
        this.newUserInfo.role = 1;
      } else {
        this.newUserInfo.role = 2;
      }
    },
    // switch添加点击时
    addSwitchClick(checked) {
      this.addSwitch = checked;
    },
    // 编辑用户
    async editUser(id) {
      // 获取用户信息返回到编辑栏上
      this.editUserInfo.id = id;
      const { data: res } = await this.$http.get(`/user/${id}`);
      if (res.status != 200) return this.$message.error("用户信息获取失败");
      this.editUserInfo.username = res.data.username;
      this.editUserInfo.role = res.data.role;
      // 显示编辑栏
      this.editUserVisiable = true;
    },
    // 编辑用户同意回调
    editUserOk() {
      this.$refs.editUserRef.validate(async (valid) => {
        if (!valid) return this.$message.error("参数不符合输入，请重新输入");
        // 发送新增用户请求
        const { data: res } = await this.$http.put(
          `/user/${this.editUserInfo.id}`,
          {
            username: this.editUserInfo.username,
            role: this.editUserInfo.role,
          }
        );
        if (res.status != 200) return this.$message.error(res.msg);
        this.$message.success("更新用户成功");
        // 重置
        this.editUserVisiable = false;
        this.$refs.editUserRef.resetFields();
        this.getUserList();
      });
    },
    // 编辑用户取消回调
    editUserCancel() {
      this.editUserVisiable = false;
      this.$message.info("编辑取消");
    },
    // 触发编辑角色的改变
    editSwitchChange(checked) {
      if (checked) {
        this.editUserInfo.role = 1;
      } else {
        this.editUserInfo.role = 2;
      }
    },
    // switch编辑点击时
    editSwitchClick(checked) {
      this.editSwitch = checked;
    },
    // 重置密码
    resetPwd(ID) {},
  },
};
</script>

<style lang="scss" scoped>
.actionSlot {
  display: flex;
  justify-content: center;
}
</style>